//
//  TTRecyclingCommitOrderViewController.m
//  TaoTuo
//
//  Created by LG on 2020/9/13.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTRecyclingCommitOrderViewController.h"
#import "TTAddressModel.h"
#import "TTCommitOrderHeaderView.h"
#import "TTMyAddressViewController.h"
#import "TTExtractAddressViewController.h"
#import "TTRecyclingHomeRightNavbarViewManager.h"
#import "TTCommonViewCell.h"
#import "TTRecyclingCommitGoodsViewCell.h"
#import "TTCellModel.h"
#import "TTRecyclingPayOrderViewController.h"
#import "TTCommitFailViewController.h"

static NSString *goodsCellID = @"goods_cell_id";
static NSString *infoCellID = @"info_cell_id";

@interface TTRecyclingCommitOrderViewController ()<UITableViewDelegate, UITableViewDataSource, TTCommitOrderHeaderViewDelegate>

@property (nonatomic, strong) TTCommitOrderHeaderView *headerView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger navCount;
@property (nonatomic, strong) TTCellModel *cellModel;

@end

@implementation TTRecyclingCommitOrderViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[TTRecyclingHomeRightNavbarViewManager sharedManager] showRightBarView];
    _navCount = self.navigationController.viewControllers.count;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (_navCount < self.navigationController.viewControllers.count) {
        [[TTRecyclingHomeRightNavbarViewManager sharedManager] hiddenRightBarView];
    }
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"提交订单";
    
    [self requestAddress];
    [self addBottomView];
    
    // header 设置完毕刷新
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshHeaderViewNotify) name:@"refreshHeaderViewNotify_key" object:nil];
    
    NSString *priceStr = [NSString stringWithFormat:@"¥%@", self.model.Price];
    self.cellModel = [TTCellModel setModelWithTitle:@"订单应付总金额" content:priceStr];
    
}

- (void)refreshHeaderViewNotify
{
    [self.headerView layoutIfNeeded];
    
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        TTRecyclingCommitGoodsViewCell *cell = [tableView dequeueReusableCellWithIdentifier:goodsCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.model;
        return cell;
    } else {
        TTCommonViewCell *cell = [tableView dequeueReusableCellWithIdentifier:infoCellID];
        cell.model = self.cellModel;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 110;
    }
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 40;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        UILabel *label = [UILabel labelWithTitle:@"    商品详情" color:UIColorHex(333333) font:[UIFont boldSystemFontOfSize:15]];
        return label;
    }
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    view.backgroundColor = UIColorHex(#F1F5F5);
    return view;
}

- (void)requestAddress
{
    NSDictionary *dic = @{
        @"param.pageIndex" : @(1),
        @"param.pageSize" : @(10)
    };
    
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getAddressList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *arr = responseObject;
        
        TTAddressModel *model = [TTAddressModel modelWithJSON:arr.firstObject];

        self.headerView = [TTCommitOrderHeaderView headerViewIsFromRecyclingWithAddress:model];
        [self.headerView setModel:model receiveType:ReceiveTypeWithMail];
        self.headerView.delegate = self;
        self.headerView.phoneTF.text = [USER_DEFAULT objectForKey:@"order_phone_key"];
        self.tableView.tableHeaderView = self.headerView;
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        
    } showLoadingInView:nil];
}

#pragma mark - TTCommitOrderHeaderViewDelegate
/// 选择收货地址
- (void)clickChooseAddressBtnWithHeaderView:(TTCommitOrderHeaderView *)headerView
{
    @weakify(self)
    if (headerView.receiveType == ReceiveTypeWithMail) {
        // 邮寄
        TTMyAddressViewController *addressVC = [[TTMyAddressViewController alloc] initWithSelectBlock:^(TTAddressModel * _Nonnull model) {
            @strongify(self)
            [self.headerView setModel:model receiveType:ReceiveTypeWithMail];
        }];
        [self.navigationController pushViewController:addressVC animated:YES];
        
    } else if (headerView.receiveType == ReceiveTypeWithSelfTake) {
        // 自提
        TTExtractAddressViewController *extractVC = [[TTExtractAddressViewController alloc] initWithSelectBlock:^(TTAddressModel * _Nonnull model) {
            @strongify(self)
            [self.headerView setModel:model receiveType:ReceiveTypeWithSelfTake];
        }];
        extractVC.addressModel = headerView.model;
        [self.navigationController pushViewController:extractVC animated:YES];
        
    }
}

/// 提交订单
- (void)commitBtnClick
{
    // 1. 验证收货地址是否填写
    if (self.headerView.tapBtn.currentTitle.length > 0) {
        [self.view makeToast:self.headerView.tapBtn.currentTitle duration:1 position:CSToastPositionCenter];
        return;
    }
//
//    // 2. 验证手机号是否填写
//    if (self.headerView.phoneTF.text.length == 0) {
//        NSString *str = [NSString stringWithFormat:@"请输入%@", self.headerView.phoneTF.placeholder];
//        [self.view makeToast:str duration:1 position:CSToastPositionCenter];
//        return;
//    }
//    // 保存输入下单人的手机号
//    [USER_DEFAULT setObject:self.headerView.phoneTF.text forKey:@"order_phone_key"];
    
    NSDictionary *dic = @{
        @"param.realName" : [TTLoginSingle sharedSingle].loginModel.RealName,
        @"param.informationGoodsId" : self.model.InformationGoodsId,
        @"param.orderSource" : @1,
        @"param.orderRemark" : self.headerView.remarkTF.text,
        @"param.receiverName" : self.headerView.model.ReceiverName,
        @"param.receiverMobile" : self.headerView.model.ReceiverMobile,
        @"param.receiverProvince" : self.headerView.model.Province,
        @"param.receiverCity" : self.headerView.model.City,
        @"param.receiverArea" : self.headerView.model.Area,
        @"param.receiverAddress" : self.headerView.model.Address,
        @"param.receiverType" : @(self.headerView.receiveType)
    };
    
    [[LLNetworkManagerTool sharedManager] postUrlString:recyclingCreateOrder_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 提交成功，去支付页面
        NSString *money_str = self.model.Price;
        NSString *address_str = [NSString stringWithFormat:@"%@%@%@%@", self.headerView.model.Province, self.headerView.model.City, self.headerView.model.Area, self.headerView.model.Address];
        NSString *nameAndphone = [NSString stringWithFormat:@"%@    %@", self.headerView.model.ReceiverName, self.headerView.model.ReceiverMobile];
        
        TTRecyclingPayOrderViewController *vc = [[TTRecyclingPayOrderViewController alloc] initWithOrderNum:responseObject[@"OrderNo"] totalMoney:money_str address:address_str nameAndphone:nameAndphone];
        [self.navigationController pushViewController:vc animated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        // 提交失败
        TTCommitFailViewController *vc = [[TTCommitFailViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    } showLoadingInView:self.view];
    
    
    
}

- (void)addBottomView
{
    UIButton *btn = [UIButton createButtonWithTitle:@"提交订单" titleColor:UIColor.whiteColor titleFont:[UIFont boldSystemFontOfSize:18] backgroundColor:UIColorHex(#6721B7) target:self action:@selector(commitBtnClick)];
    [self.view addSubview:btn];
    if (Tabbar_Bottom_height > 0) {
        btn.contentEdgeInsets = UIEdgeInsetsMake(-20, 0, 0, 0);
    }
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        make.top.equalTo(self.tableView.mas_bottom);
        make.left.right.equalTo(self.view);
    }];
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        [_tableView registerClass:[TTCommonViewCell class] forCellReuseIdentifier:infoCellID];
        [_tableView registerClass:[TTRecyclingCommitGoodsViewCell class] forCellReuseIdentifier:goodsCellID];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.mas_topLayoutGuideBottom);
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(-50);
            make.left.right.equalTo(self.view);
        }];
    }
    return _tableView;
}

@end
